<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/19
 * Time: 16:19
 */

namespace Game\Module;


use Game\Config\Config;
use Game\Traits\Singleton;
/**
 * 日志处理单例
 * Class Logger
 * @package Game\Library
 */
class Logger
{
    use Singleton;
    protected static $dirCreated;
    private $errorMessage;

    public function debug($message, $level='DEBUG'){
        $this->log($message,$level,'debug');
    }

    public function error($message, $level='ERROR'){
        $this->log($message,$level,'error');
    }

    public function info($message, $level='INFO'){
        $this->log($message,$level,'info');
    }

    public function socket($message, $level='INFO'){
        $this->log($message,$level,'socket');
    }

    public function log($message ,$level = "INFO", $type="info"){
        $this->createDir();
        $logdir = Config::Log_Dir.'/'.$type.'-'.date("Y-m-d").'.log';
        if (is_array($message)) {
            $message = json_encode($message, JSON_UNESCAPED_UNICODE);
        }
        $content = "[" . date("Y-m-d H:i:s") . "] [".$level."] ". $message.PHP_EOL;
        file_put_contents($logdir, $content, FILE_APPEND);
    }



    private function createDir() {
        // Do not try to create dir if it has already been tried.
        if (self::$dirCreated) {
            return;
        }

        if (null !== Config::Log_Dir && !is_dir(Config::Log_Dir)) {
            $this->errorMessage = null;
            set_error_handler(array($this, 'customErrorHandler'));
            $status = mkdir(Config::Log_Dir, 0777, true);
            restore_error_handler();
            if (false === $status && !is_dir(Config::Log_Dir)) {
                throw new \UnexpectedValueException(sprintf('There is no existing directory at "%s" and its not buildable: '.$this->errorMessage, Config::Log_Dir));
            }
        }
        self::$dirCreated = true;
    }

    private function customErrorHandler($code, $msg)
    {
        $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);
    }
}